<template>
  <div class="countContainer" :class="{ isDark: isDark }">
    <div class="item">
      <span class="name">{{ $t('count.words') }}</span>
      <span class="value">{{ words }}</span>
    </div>
    <div class="item">
      <span class="name">{{ $t('count.nodes') }}</span>
      <span class="value">{{ num }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useI18n } from 'vue-i18n'
import { storeToRefs } from 'pinia'
import { useMainStore } from '@/stores'
import { useEventBus } from '@/hooks'

// 组合式API设置
const { t } = useI18n()
const { $on, $off, $emit, $once } = useEventBus()
const store = useMainStore()

// Props
const props = defineProps({
  mindMap: {
    type: Object,
    default: null
  }
})

// 从store获取响应式状�?
const { isDark } = storeToRefs(store)

// 响应式数�?
const textStr = ref('')
const words = ref(0)
const num = ref(0)

// 字数及节点数量统�?
let countEl = document.createElement('div')

// 生命周期钩子
onMounted(() => {
  $on('data_change', onDataChange)
  if (props.mindMap) {
    onDataChange(props.mindMap.getData())
  }
})

onBeforeUnmount(() => {
  $off('data_change', onDataChange)
})

// 方法
const onDataChange = (data) => {
  textStr.value = ''
  words.value = 0
  num.value = 0
  walk(data)
  countEl.innerHTML = textStr.value
  words.value = countEl.textContent.length
}

const walk = (data) => {
  if (!data) return
  num.value++
  textStr.value += String(data.data.text) || ''
  if (data.children && data.children.length > 0) {
    data.children.forEach(item => {
      walk(item)
    })
  }
}
</script>

<style lang="less" scoped>
.countContainer {
  padding: 0 12px;
  position: fixed;
  left: 20px;
  bottom: 20px;
  background: hsla(0, 0%, 100%, 0.8);
  border-radius: 2px;
  opacity: 0.8;
  height: 22px;
  line-height: 22px;
  font-size: 12px;
  display: flex;

  &.isDark {
    background: #262a2e;

    .item {
      color: hsla(0, 0%, 100%, 0.6);
    }
  }

  .item {
    color: #555;
    margin-right: 15px;

    &:last-of-type {
      margin-right: 0;
    }

    .name {
      margin-right: 5px;
    }
  }
}

@media screen and (max-width: 900px) {
  .countContainer {
    display: none;
  }
}
</style>
